<template>
    <div class="financial">
        <Header :title="t('financial.order.list')" background-color="#FFFFFF" font-color="#000">
            <template #left>
                <van-icon name="arrow-left" size="25px" class="icon-left" @click="goBack()" />
            </template>
        </Header>
        <div class="bg">
            <ul class="circle">
                <li></li>
                <li></li>
                <li></li>
            </ul>
            <div class="dot">
                <ul>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                    <li></li>
                </ul>
            </div>
        </div>
        <div class="title">
            <div class="funds">
                <div class="left">
                    <div class="up">{{ t('financial.allFinancialAmt') }}</div>
                    <div class="down">
                        {{ funds.allFinancialAmt || Number(0).toFixed(4) }} <span>USDT</span>
                    </div>
                </div>
                <div class="right">
                    <!-- <div class="order">{{ t('financial.book') }}</div> -->
                </div>
            </div>
            <div class="exports">
                <template v-for="(value, key) of funds" :key="key">
                    <div class="items" v-if="key != 'allFinancialAmt'">
                        <div class="value">{{ value || 0 }}</div>
                        <div class="key">{{ t(`financial.${key}`) }}</div>
                    </div>
                </template>
            </div>
        </div>
        <nav>
            <van-dropdown-menu>
                <van-dropdown-item v-model="value1" @change="onValueChange" :options="option1" />
            </van-dropdown-menu>
        </nav>
        <main>
            <ul>
                <template v-for="(item, index) in historyList" :key="index">
                    <li>
                        <div class="top">
                            <div class="right">
                                <span>{{ item.financial.name }}</span>
                            </div>
                            <div class="left">
                                <div class="btn" @click="showFinancialForm(item)">
                                    {{ item.status == 0 ? t('financial.order.addBreach') : t('financial.order.statu2') }}
                                </div>
                            </div>
                        </div>
                        <div class="bottom">
                            <div class="items">
                                <div class="key">{{ t('financial.order.allProfit') }}</div>
                                <div class="value">{{ item.allProfit }}</div>
                            </div>
                            <div class="items">
                                <div class="key">{{ t('financial.order.buyAmt') }}</div>
                                <div class="value">{{ item.buyAmt }}</div>
                            </div>
                            <div class="items">
                                <div class="key">{{ t('financial.order.nowProfit') }}</div>
                                <div class="value">{{ item.nowProfit }}</div>
                            </div>
                            <div class="items">
                                <div class="key">{{ t('financial.order.settleTime') }}</div>
                                <div class="value">{{ update(item.settleTime) }}</div>
                            </div>
                            <div class="items">
                                <div class="key">{{ t('financial.order.realRate') }}</div>
                                <div class="value">{{ `${Number(item.realRate * 100).toFixed(2)} %` }}</div>
                            </div>
                            <div class="items">
                                <div class="key">{{ t('financial.order.status') }}</div>
                                <div class="value">{{ item.status == 0 ? t('financial.order.statu1') :
                                    t('financial.order.statu2') }}</div>
                            </div>
                        </div>
                    </li>
                </template>
            </ul>
        </main>
        <!-- 合约 -->
        <Dialog v-model="financialFormShow" :click-mask-is-close="false" :loading="isFinanciaLoading"
            :confirm="t('confirm')" @onConfirm="onFinancialFormConfirm" @onCancel="onFinancialFormCancel"
            :cancel="t('cancel')">
            <div class="leftBox">
                <div class="entrustsBox">
                    <h3>
                        {{ t('financial.order.addBreach') }}
                    </h3>
                    <div class="entrusts a_re">
                        <van-radio-group v-model="financialForm.type" direction="horizontal">
                            <van-radio :name="0">{{ t('financial.order.shouyi') }}</van-radio>
                            <van-radio :name="1">{{ t('financial.order.benjin') }}</van-radio>
                        </van-radio-group>
                        <div class="amt">
                            <input type="number" class="inputAmt" v-model="financialForm.amt"
                                @input="changeAmt(financialForm.amt)"
                                :placeholder="financialForm.type == 0 ? t('financial.order.shouyi') : t('financial.order.benjin')">
                        </div>
                    </div>
                    <!-- 提示违约金 -->
                    <div class="rules" v-show="financialForm.type == 1">
                        <p>
                            {{ t('financial.rules1') }}
                        </p>
                    </div>
                </div>
            </div>
        </Dialog>
        <Dialog v-model="secondDialog" :click-mask-is-close="false" :confirm="t('confirm')" :cancel="t('cancel')"
            @onConfirm="onSecondDialog" @onClose="onFinancialFormClose">
            <div class="secondDialog">
                <h3>
                    {{ t('financial.order.addBreach') }}
                </h3>
                <ul>
                    <li>
                        <div class="key">
                            {{ t('financial.order.amt') }}
                        </div>
                        <div class="value">
                            {{ financialForm.amt }}
                        </div>
                    </li>
                    <li>
                        <div class="key">
                            {{ t('financial.order.type') }}
                        </div>
                        <div class="value">
                            {{ financialForm.type == 0 ? t('financial.order.shouyi') : t('financial.order.benjin') }}
                        </div>
                    </li>
                    <li>
                        <div class="key">
                            {{ t('financial.order.breachRate') }}
                        </div>
                        <div class="value">
                            {{ `${Number(breachFrom.breachRate)} %` }}
                        </div>
                    </li>
                    <li>
                        <div class="key">
                            {{ t('financial.order.breachAmt') }}
                        </div>
                        <div class="value">
                            {{ Number(breachFrom.breachAmt) }}
                        </div>
                    </li>
                </ul>
            </div>
        </Dialog>
    </div>
</template>

<script setup>
import Header from "@/components/Header/index.vue";
import Dialog from "@/components/Dialog/index.vue";
import useLanguage from '@/hooks/useLanguage';
import { marketApi, userApi, fundsApi } from '@/api'
import { reactive, watch, computed, ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
import { showNotify } from 'vant';
import { storeToRefs } from 'pinia'
import { UserStore } from '@/store/user';
import { useRouter } from 'vue-router'

const { t } = useLanguage()
const userStore = UserStore()
const { userInfo, cateId } = storeToRefs(userStore)
const router = useRouter()

const funds = reactive({
    allFinancialAmt: '',
    allFinancialProfit: '',
    custodyOrderCount: '',
    expectedFinancialProfit: '',
})

// 理财资金总览
async function getUserFinancialInfo() {
    const { code, data, success } = await fundsApi.getUserFinancialInfo()
    if (code == 20000 && success) {
        Object.assign(funds, data)
    }
}


const value1 = ref(-1);
const option1 = [
    { text: t('financial.order.statu3'), value: -1 },
    { text: t('financial.order.statu1'), value: 0 },
    { text: t('financial.order.statu2'), value: 1 },
];

// 产品
const historyList = ref([])
const postData = reactive({
    status: '',
    pageNum: 1,
    pageSize: 10,
})
const pages = ref()
const isNoList = ref(false)
async function getFinancialHistory() {
    const { code, data, success } = await fundsApi.getFinancialHistory(postData)
    if (code == 20000 && success) {
        console.log(data);
        pages.value = data.pages
        if (data.records.length > 0) {
            data.records.map((item) => historyList.value.push(item))
        } else {
            historyList.value = []
        }
    }
}

function onValueChange(value) {
    if (value == -1) {
        postData.status = ''
    } else {
        postData.status = value
    }
    historyList.value = []
    getFinancialHistory()
}




// 资金提取
// 提取资金的参数
const financialForm = reactive({
    fhId: '',
    amt: '',
    type: 0,
})

const breachFrom = reactive({
    breachRate: '', // 违约金比例（提取类型为本金时需要传，下同）
    breachAmt: '', // 违约金金额
})

// 提取资金的弹出框
const financialFormShow = ref(false)
const isFinanciaLoading = ref(false) // 按钮的加载状态
const disabled = ref(true) // 输入框的禁用


const curItem = reactive({})
// 弹出框展示之前
function showFinancialForm(item) {
    if (item.status == 1) {
        showNotify({
            message: t('financial.order.statu2'),
            type: 'danger',
        })
        return
    }
    Object.assign(curItem, item)
    // 保存提取订单的参数
    financialForm.fhId = item.id
    disabled.value = false
    financialFormShow.value = true
}

// 修正收益金额
function changeAmt(val) {
    if (val < 0) {
        financialForm.amt = ''
    }
    if (financialForm.type == 0) {
        // 收益
        if (val > curItem.nowProfit) {
            financialForm.amt = curItem.nowProfit
        }
    } else {
        // 本金
        if (val > curItem.buyAmt) {
            financialForm.amt = curItem.buyAmt
        }
    }
}

// 关闭弹出框
function onFinancialFormClose() {
    financialForm.amt = ''
    financialForm.fhId = ''
    financialForm.type = 0
    breachFrom.breachAmt = ''
    breachFrom.breachRate = ''
}

async function onFinancialFormConfirm() {
    if (financialForm.type == 0) {
        const { code, data, success } = await fundsApi.addBreach(financialForm)
        if (code == 20000 && success) {
            showNotify({
                message: t('financial.order.success'),
                type: 'success'
            })
        } else {
            showNotify({
                message: t('financial.order.erroe'),
                type: 'danger'
            })
        }
        getUserFinancialInfo()
        historyList.value = []
        getFinancialHistory()
    } else {
        if (financialForm.amt == '') {
            showNotify({
                message: t('financial.order.noEmpty'),
                type: 'danger'
            })
            return
        }
        // 计算违约金
        getBreachAmt()
    }
}

function onFinancialFormCancel() {

}


async function getBreachAmt() {
    const obj = { fhId: financialForm.fhId, amt: financialForm.amt };
    const { code, data, success } = await fundsApi.getBreachAmt(obj)
    if (code == 20000 && success) {
        breachFrom.breachAmt = data.breachAmt
        breachFrom.breachRate = data.breachRate
    }
    secondDialog.value = true
}


// 二级弹窗
const secondDialog = ref(false)
async function onSecondDialog() {
    const { code, data, success } = await fundsApi.addBreach({ ...financialForm, ...breachFrom })
    if (code == 20000 && success) {
        showNotify({
            message: t('financial.order.success'),
            type: 'success'
        })
    } else {
        showNotify({
            message: t('financial.order.erroe'),
            type: 'danger'
        })
    }
    getUserFinancialInfo()
    historyList.value = []
    getFinancialHistory()
}





// 辅助函数
function goBack() {
    router.go(-1)
}

function handleScroll(e) {
    const scrollTop = document.scrollingElement.scrollTop // 滚动条的位置
    const windowHeitht = document.scrollingElement.clientHeight // 在页面上返回内容的可视高度
    const scrollHeight = document.scrollingElement.scrollHeight // 返回整个元素的高度（包括带滚动条的隐蔽的地方）

    // 是否滚动到底部的判断
    if ((Math.round(scrollTop) + windowHeitht) == scrollHeight) {
        // console.log('到底部了');
        if (postData.pageNum < pages.value) {
            postData.pageNum++
            getFinancialHistory()
            isNoList.value = false
        } else {
            isNoList.value = true
        }
    }
    // console.log({ scrollTop, windowHeitht, scrollHeight }, (Math.round(scrollTop) + windowHeitht) == scrollHeight);

}

const update = (date) => {
    const time = new Date(date).getTime()
    const second = new Date(date).getSeconds()
    const minute = new Date(date).getMinutes()
    const hour = new Date(date).getHours()
    const curdate = new Date(date).getDate()
    const mounth = new Date(date).getMonth() + 1
    const year = new Date(date).getFullYear()
    const newDate = `${year} ${mounth < 10 ? '0' + mounth : mounth}-${curdate < 10 ? '0' + curdate : curdate} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}:${second < 10 ? '0' + second : second}`
    return newDate
}

onMounted(() => {
    getUserFinancialInfo()
    getFinancialHistory()
    nextTick(() => {
        document.addEventListener('scroll', handleScroll)
    })
})

onBeforeUnmount(() => {
    document.removeEventListener('scroll', handleScroll)
})
</script>
<style lang="less" scoped>
.financial {
    position: relative;

    .bg {
        width: 100%;
        height: 200px;
        background: linear-gradient(#1A62C2, #2594f5);
        position: absolute;
        overflow: hidden;
        z-index: -1;

        .circle {
            height: 100%;
            position: relative;

            li {
                position: absolute;
                top: 90%;
                left: 50%;
                width: 260px;
                height: 260px;
                border: 1px solid rgba(255, 255, 255, 0.5);
                border-radius: 50%;
            }

            li:nth-child(1) {
                transform: translate(-50%, -50%) scale(1);
            }

            li:nth-child(2) {
                transform: translate(-50%, -50%) scale(0.8);
            }

            li:nth-child(3) {
                transform: translate(-50%, -50%) scale(0.6);
            }
        }

        .dot {
            position: absolute;
            width: 100%;
            height: 200px;
            top: 0;

            ul {
                height: 100%;
                position: relative;

                li {
                    position: absolute;
                    border-radius: 50%;
                }

                li:nth-child(1) {
                    width: 5px;
                    height: 5px;
                    top: 35%;
                    left: 15%;
                    background-color: rgba(255, 255, 255, 0.5);
                }

                li:nth-child(2) {
                    width: 5px;
                    height: 5px;
                    top: 58%;
                    left: 91%;
                    background-color: rgba(255, 255, 255, 0.2);
                }

                li:nth-child(3) {
                    width: 5px;
                    height: 5px;
                    top: 75%;
                    left: 65%;
                    background-color: rgba(255, 255, 255, 0.5);
                }

                li:nth-child(4) {
                    width: 5px;
                    height: 5px;
                    top: 25%;
                    left: 75%;
                    background-color: rgba(255, 255, 255, 0.5);
                }

                li:nth-child(5) {
                    width: 5px;
                    height: 5px;
                    top: 10%;
                    left: 85%;
                    background-color: rgba(255, 255, 255, 0.5);
                }

                li:nth-child(6) {
                    width: 5px;
                    height: 5px;
                    top: 30%;
                    left: 35%;
                    background-color: rgba(255, 255, 255, 0.5);
                }
            }
        }
    }

    .title {
        width: 100%;
        height: 200px;

        .funds {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px 0px 20px 30px;

            .left {
                flex: 2;
                color: rgba(255, 255, 255, 0.8);

                .up {
                    font-size: 18px;
                    font-weight: 200;
                }

                .down {
                    font-size: 28px;
                    font-weight: 500;

                    span {
                        font-weight: 100;
                        font-size: 24px;
                    }
                }
            }

            .right {
                flex: 1;
                color: #6D86B9;

                .order {
                    padding: 10px 0px 10px 10px;
                    border-radius: 22px 0px 0px 22px;
                    text-align: center;
                    background-color: rgba(255, 255, 255, 0.7);
                }
            }
        }

        .exports {
            width: 100%;
            height: 80px;
            background-color: rgba(255, 255, 255, 0.3);

            display: grid;
            grid-template-columns: repeat(3, minmax(0, 1fr));

            .items {
                color: rgba(255, 255, 255, 0.8);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
            }
        }
    }

    nav {
        .van-dropdown-menu {
            /deep/.van-dropdown-menu__bar {
                justify-content: flex-start;

                .van-dropdown-menu__item {
                    flex: none;
                }
            }
        }
    }

    main {
        padding: 20px 10px 1px;
        background-color: #F7F6FC;

        ul {
            li {
                background-color: #fff;
                margin-bottom: 20px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;

                .top {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;
                    padding: 10px;
                    box-sizing: border-box;



                    .right {
                        background-color: #FEDD06;
                        padding: 5px 10px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        font-weight: 900;
                    }

                    .left {
                        .btn {
                            background-color: #00ABFD;
                            color: #fff;
                            padding: 5px 15px;
                            border-radius: 5px;
                            box-sizing: border-box;
                        }
                    }

                }

                .bottom {
                    display: grid;
                    grid-template-columns: repeat(3, minmax(0, 1fr));
                    column-gap: 40px;
                    margin-top: 10px;

                    .items {
                        display: flex;
                        flex-direction: column;
                        justify-content: center;
                        align-items: center;

                        .key {
                            font-size: 14px;
                            white-space: nowrap;
                            text-align: center;
                            margin-bottom: 10px;
                        }

                        .value {
                            margin-bottom: 16px;
                            color: #4DA1BD;
                            font-size: 14px;
                            text-align: center;
                        }
                    }
                }
            }
        }
    }

    .leftBox {
        padding-top: 10px;

        .entrustsBox {
            h3 {
                text-align: center;
            }

            .entrusts {
                margin-top: 40px;

                .amt {
                    padding: 20px 0px 10px;
                }

                .input {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 20px 0px 10px;

                    input {
                        font-size: 12px;
                    }

                    span {
                        font-size: 12px;
                    }
                }
            }

            .rules {
                margin-top: 10px;
                font-size: 12px;

                p {
                    span {
                        color: #00ABFD;
                    }
                }
            }

            .pad_l_10 {
                padding-left: 10px !important;
            }
        }
    }

    .secondDialog {
        h3 {
            text-align: center;
        }

        ul {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 100%;

            li {
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 5px 0px;
            }
        }
    }
}
</style>